package com.wl.dzt.sys.util;

import com.wl.dzt.sys.util.json.Json;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public class YPSmsUtil {

    protected static Logger log = LoggerFactory.getLogger(YPSmsUtil.class);

    private static String NORMAL = "0";
    private static String appkey;
    private static String smsurl;

    static {
        Map<String, String> configMap = ResourceUtils.loadProperties("sms-config.properties");
        appkey = configMap.get("yp.sms.smsurl");
        smsurl = configMap.get("yp.sms.appkey");
    }

    public static void send(String phone, String template, String... args) {
        String msgText = String.format(template.replace("【变量】", "%s"), args);
        new Thread(() -> SendSms(msgText, phone)).start();
    }

    private static boolean SendSms(String msgText, String phone) {
        boolean flag = false;
        OkHttpClient client = new OkHttpClient();
        try {
            FormBody.Builder builder = new FormBody.Builder();
            builder.add("apikey", appkey).add("mobile", phone)
                    .add("text", msgText);
            FormBody body = builder.build();
            Request request = new Request.Builder().url(smsurl).post(body)
                    .build();
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            log.debug("phone[{}]短信返回result[{}]",phone,result);
            Map<String, Object> reultMap = Json.recover(result, Map.class);
            if (null != reultMap) {
                String code3 = String.valueOf(reultMap.get("code"));
                if (response.code() == 200 && NORMAL.equals(code3)) {
                    return true;
                }
            }
        } catch (Exception e) {
            log.error("短信验证码发送异常", e);
            flag = false;
        }
        return flag;
    }

}
